import 'dart:async';
import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Token.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/sp_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:fsuper/fsuper.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:tobias/tobias.dart' as tobias;

import 'home/mcu_web.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends StateWithLifecycle<LoginPage> {
  bool _isLoading = false;
  String _phone, _password;
  bool _isObscure = true;
  final _formKey = GlobalKey<FormState>();
  var _phoneController = TextEditingController();

  List _loginMethod = [
    {
      "id": 0,
      "title": "QQ",
      "icon": FontAwesomeIcons.qq,
      "color": Color(0XFF10A0E6),
    },
    {
      "id": 1,
      "title": "微信",
      "icon": FontAwesomeIcons.weixin,
      "color": Color(0XFF01D00E),
    },
    {
      "id": 2,
      "title": "新浪微博",
      "icon": FontAwesomeIcons.weibo,
      "color": Color(0XFFF86263),
    }
  ];

  Future initDatas() async {
    String userStr = await SpUtils.get(SpUtils.SP_USER, "");
    if ("" != userStr) {
      User user = User.fromJson(json.decode(userStr));
      _phone = user.phone;
      _phoneController.value = TextEditingValue(text: _phone ?? "");
    }
  }

  @override
  void onResume() {
    super.onResume();
    initDatas();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey,
        child: ListView(
            padding: EdgeInsets.symmetric(horizontal: 22.0),
            children: <Widget>[
              SizedBox(height: kToolbarHeight),
              titleBuild(),
              titleLine(),
              privacyWidget(),
              SizedBox(height: 10.0),
              buildPhoneTextField(),
              buildPasswordTextField(context),
              buildForgetPasswordText(context),
              SizedBox(height: 20.0),
              buildLoginButton(context),
              SizedBox(height: 20.0),
              buildOtherLoginText(),
              buildOtherMethod(context),
              buildRegisterText(context)
            ]),
      ),
    );
  }

  Widget titleBuild() {
    return Padding(
      padding: EdgeInsets.all(8),
      child: Text(
        '登录',
        style: TextStyle(fontSize: 32),
      ),
    );
  }

  Widget titleLine() {
    return Padding(
      padding: EdgeInsets.only(left: 12.0),
      child: Align(
        alignment: Alignment.bottomLeft,
        child: Container(
          color: Colors.black,
          width: 30.0,
          height: 3.0,
        ),
      ),
    );
  }

  ///隐私协议
  Widget privacyWidget() {
    return FSuper(
      textAlign: TextAlign.left,
      margin: EdgeInsets.only(left: 12, top: 10),
      spans: [
        TextSpan(
          text: "为了实现社交分享和第三方登录功能，我们使用了MobTech的ShareSDK产品,登录即代表您已同意",
          style: TextStyle(fontSize: 11),
        ),
        TextSpan(
            text: "《MobTech隐私政策》",
            style: TextStyle(
              color: Colors.blue,
              fontSize: 11,
            ),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (_) {
                    return WebInfoPage(
                        "MobTech隐私政策", "http://www.mob.com/about/policy",
                        type: "web");
                  }),
                );
              }),
      ],
    );
  }

  /// 手机号输入框
  Widget buildPhoneTextField() {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: TextField(
        controller: _phoneController,
        decoration: InputDecoration(labelText: '手机号/邮箱', hintText: '请输入手机号或邮箱'),
      ),
    );
  }

  ///密码输入框
  Widget buildPasswordTextField(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: TextFormField(
        onSaved: (String value) => _password = value,
        obscureText: _isObscure,
        // ignore: missing_return
        validator: (String value) {
          if (value.isEmpty) {
            return '请输入密码';
          }
        },
        decoration: InputDecoration(
          labelText: '密码',
          suffixIcon: IconButton(
              icon: Icon(
                _isObscure ? Icons.visibility : Icons.visibility_off,
              ),
              onPressed: () {
                setState(() {
                  _isObscure = !_isObscure;
                });
              }),
        ),
      ),
    );
  }

  ///登录按钮
  Align buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45.0,
        width: 270.0,
        child: RaisedButton(
          child: Text(
            '登录',
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          color: Theme.of(context).accentColor,
          onPressed: () {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              login(null, "phone");
            }
          },
          shape: StadiumBorder(
              side: BorderSide(color: Theme.of(context).accentColor)),
        ),
      ),
    );
  }

  ///点击登录
  void login(Map map, String type) async {
    Map<String, String> params = Map();

    if (type == "qq") {
      params['qqId'] = map["userID"];
    } else if (type == "wx") {
      params['wxId'] = map["openid"];
    } else if (type == "weibo") {
      params['wbId'] = map["userId"];
    } else {
      String userName = _phoneController.text;
      if (userName.isEmpty) {
        Toast.show("请输入手机号或邮箱");
        return;
      }
      params["userName"] = _phoneController.text;
      params["password"] = _password;
      closeLoading = Toast.loading("登录中...");
    }
    if (null != map) {
      params['imgUrl'] = map["icon"];
      params['userName'] = map["nickname"];
      params['sex'] = map["gender"] == "0" ? "男" : "女";
    }
    if (params.isEmpty && "alipay" != type) {
      Toast.show('请选择一种登录方式');
      return;
    }
    submitPrivacyGrantResult();
    Http.post(Api.LOGIN_AUTH, params: params, successCallBack: (data) {
      Token token = Token.fromJson(json.decode(data));
      if (null != token) {
        SpUtils.put(SpUtils.SP_TOKEN, token.token);
      }
      getUserInfo();
    }, errorCallBack: (msg) {
      if (null != closeLoading) {
        closeLoading();
      }
      Toast.show(msg);
    });
  }

  ///登录成功后获取用户信息
  void getUserInfo() {
    Http.get(Api.URL_INFO, successCallBack: (data) {
      if (null != closeLoading) {
        closeLoading();
      }
      Toast.show('登录成功');
      Routers.router.navigateTo(context, Routers.PAGE_MAIN,
          transition: TransitionType.inFromRight, clearStack: true);
    }, errorCallBack: (msg) {
      Toast.show(msg);
      if (null != closeLoading) {
        closeLoading();
      }
    });
  }

  Padding buildForgetPasswordText(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Align(
        alignment: Alignment.centerRight,
        child: FlatButton(
          child: Text(
            '忘记密码？',
            style: TextStyle(fontSize: 14.0, color: Colors.grey),
          ),
          onPressed: () {
            Routers.router.navigateTo(
                context, "${Routers.PAGE_CHECKPHONE}?title=wjmm",
                transition: TransitionType.inFromRight);
          },
        ),
      ),
    );
  }

  Align buildOtherLoginText() {
    return Align(
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(left: 10, right: 10),
              height: 1,
              width: 60,
              color: Color(0XFFDDDDDD),
            ),
            Text(
              '其他账号登录',
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14.0,
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 10, right: 10),
              height: 1,
              width: 60,
              color: Color(0XFFDDDDDD),
            ),
          ],
        ));
  }

  ///三方登录按钮列表
  ButtonBar buildOtherMethod(BuildContext context) {
    return ButtonBar(
      alignment: MainAxisAlignment.center,
      children: _loginMethod
          .map(
            (item) => Builder(
              builder: (context) {
                return _thirdWidget(item);
              },
            ),
          )
          .toList(),
    );
  }

  ///三方登录按钮
  Widget _thirdWidget(Map map) {
    return FSuper(
      width: 46,
      height: 46,
      backgroundColor: map['color'],
      corner: Corner.all(23),
      child1: Icon(map['icon'], color: Colors.white),
      child1Alignment: Alignment.center,
      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
      shadowColor: map['color'],
      shadowBlur: 2,
      onClick: () {
        switch (map['id']) {
          case 0:
            _thirdLogin(context, "qq");
            break;
          case 1:
            _thirdLogin(context, "wx");
            break;
          case 2:
            _thirdLogin(context, "weibo");
            break;
        }
      },
    );
  }

  CancelFunc closeLoading;

  ///三方登录执行方法
  void _thirdLogin(BuildContext context, String type) {
    ShareSDKPlatform platforms;
    if (type == "qq") {
      platforms = ShareSDKPlatforms.qq;
    } else if (type == "wx") {
      platforms = ShareSDKPlatforms.wechatSession;
    } else if (type == "weibo") {
      platforms = ShareSDKPlatforms.sina;
    }
    closeLoading = Toast.loading("登录中...");
    SharesdkPlugin.getUserInfo(platforms,
        (SSDKResponseState state, Map user, SSDKError error) {
      print("登录结果：$user");
      if (state == SSDKResponseState.Success) {
        if (null != user && user.containsKey("dbInfo")) {
          login(json.decode(user["dbInfo"]), type);
        }
      } else if (state == SSDKResponseState.Cancel) {
        if (null != closeLoading) {
          closeLoading();
        }
        Toast.show("操作已取消");
      } else {
        if (null != closeLoading) {
          closeLoading();
        }
        Toast.show("登录失败");
      }
    });
  }

  Widget buildRegisterText(BuildContext context) {
    return FSuper(
      margin: EdgeInsets.only(top: 10),
      width: double.infinity,
      height: 36,
      child2: Text('没有账号？'),
      child2Margin: EdgeInsets.only(right: 32),
      child1: Text(
        '点击注册',
        style: TextStyle(color: Theme.of(context).accentColor),
      ),
      child1Margin: EdgeInsets.only(left: 32),
      onChild1Click: () {
        Routers.router.navigateTo(
            context, "${Routers.PAGE_REGIST}?message=${_phoneController.text}",
            transition: TransitionType.inFromRight);
      },
    );
  }

  submitPrivacyGrantResult() async {
    bool agree = await SpUtils.get(SpUtils.SP_MOB, false);
    if (agree) {
      return;
    }
    SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {
      if (success == true) {
        SpUtils.put(SpUtils.SP_MOB, true);
      } else {
        SpUtils.put(SpUtils.SP_MOB, false);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _phoneController.dispose();
  }
}
